package {
	//import net.sanative.connectors.SmtpSocket;
	import com.datacurl.DataManager;
	import com.oosterwijk.irc.FlexIrcClient;
	import com.oosterwijk.irc.client.ChannelWindow;
	
	import flash.desktop.NativeApplication;
	import flash.desktop.SystemTrayIcon;
	import flash.display.Bitmap;
	import flash.display.NativeMenu;
	import flash.display.NativeMenuItem;
	import flash.events.Event;
	import flash.utils.Timer;
	
	import flexlib.containers.SuperTabNavigator;
	
	import mx.collections.ArrayCollection;
	import mx.containers.HBox;
	import mx.containers.TitleWindow;
	import mx.containers.VBox;
	import mx.containers.VDividedBox;
	import mx.controls.Alert;
	import mx.controls.DataGrid;
	import mx.controls.HTML;
	import mx.controls.Image;
	import mx.controls.ProgressBar;
	import mx.controls.TextInput;
	import mx.controls.sliderClasses.Slider;
	import mx.core.Application;
	import mx.effects.Fade;
	import mx.events.EffectEvent;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;
	import mx.utils.StringUtil;
	
	import net.sanative.managers.*;
	import net.sanative.ui.*;
	import net.sanative.woot.*;
	
	public class Yawn extends Application {
		
		public function Yawn():void {
			super();
			//um.addEventListener("isUpdating", initUpgrade);
			//um.addEventListener("updaterComplete", stopListeningForUpdates);
			setupSystemTrayIcon();
			
			currentWootService.url = "http://www.woot.com/blog/salerss.aspx";
			currentWootService.resultFormat = "object";
			currentWootService.requestTimeout = 60;
			
			blogService.url = "http://www.woot.com/blog/rss.aspx";
			blogService.resultFormat = "object";
			blogService.requestTimeout = 60;
			
			currentWootService.addEventListener(FaultEvent.FAULT, faultWootService);
			currentWootService.addEventListener(ResultEvent.RESULT, handleCurrentWootService);
			blogService.addEventListener(FaultEvent.FAULT, faultWootService);
			blogService.addEventListener(ResultEvent.RESULT, handleWootService);
			
			//myEmail.Username = "";
			//myEmail.Password = "";
			
			reloadWoot(null);
			
			wootTimer.addEventListener("timer", reloadWoot);
			wootTimer.start();
			contentBox.setStyle('backgroundAlpha', currentOpacity);
			
			//sendEmail();
		}
		
		//icon for the system tray
		[Embed('assets/images/trayicons/yawn.png')]
		private static var sysTrayIcon16:Class;
		
		//icon for the system tray
		[Embed('assets/images/trayicons/yawn.png')]
		private static var sysTrayIcon16Alert:Class;
		
		private var sysTrayIcon:SystemTrayIcon = NativeApplication.nativeApplication.icon as SystemTrayIcon;
		
		[Bindable]
		[Embed(source="assets/images/loading.gif")]
		public var loaderImage:Class;
		
		[Bindable]
		[Embed(source="assets/images/yawn.png")]
		public var yawnLogo:Class;
		
		// the buttons and title
		[Bindable]
		public var titleControls:TitleControls = new TitleControls();
		
		[Bindable]
		[Embed(source="assets/images/soldout.gif")]
		public var soldOutImageSrc:Class;
		
		public var currentDiscussion:HTML = new HTML();
		
		public var currentWootDesc:HTML = new HTML();
		
		public var soldOutImg:Image = new Image();
		
		[Bindable]
		public var currentWootService:HTTPService = new HTTPService();

		public var lastWootResult:Object = new Object();
		
		public var blogService:HTTPService = new HTTPService();
		
		[Bindable]
		protected var blogItems:ArrayCollection = new ArrayCollection();

		public var dataRefreshIcon:Image = new Image();
		
		public var contentBox:VDividedBox = new VDividedBox();
		
		public var wootPodcast:WootPodcast = new WootPodcast();
		
		public var currentWoot:VBox = new VBox();
		
		public var percentSold:ProgressBar = new ProgressBar();
		
		[Bindable]
		public var fadeOut:Fade = new Fade();
		
		public var tabnav_woots:SuperTabNavigator = new SuperTabNavigator();
		
		public var hb_chat:HBox = new HBox();
		
		public var last10Woots:DataGrid = new DataGrid();
		
		public var wootcastProgress:ProgressBar = new ProgressBar();
		
		[Bindable]
		public var nickName:TextInput = new TextInput();
		
		public var dataManager:DataManager = new DataManager();  //dw
			
		//the background of the app
		[Bindable]
		public var bgBox:BackgroundBox = new BackgroundBox();
		
		//the slider to change opacity
		[Bindable]
		public var opacitySlider:Slider = new Slider();
		
		protected var wootTimer:Timer = new Timer(30000);
		
		//[Bindable]
		//private var myEmail:SmtpSocket = new SmtpSocket;
		
		//[Bindable]
		//protected var myEmailHost:String = "192.168.168.2";
		
		//[Bindable]
		//protected var myEmailHostPort:int = 25;
		
		[Bindable]
		protected var podcastURL:String;
		
		[Bindable]
		protected var currentOpacity:Number = 1;
		
		//create new Update Manager and give it a URL
		//private var um:UpdateManager = new UpdateManager("http://www.sanative.net/yawn/version.xml");
		
		public var wootIRC:ChannelWindow = new ChannelWindow();
		
		public var ircLoginWindow:TitleWindow = new TitleWindow();
		
		public var chatConnect:VBox = new VBox();
		
		/*
		private function sendEmail():void {
			myEmail.connect(myEmailHost, myEmailHostPort);
		}
		*/
		
		private function initUpgrade(evt:Event): void {
			//set all windows hidden if we are in upgrade mode
			//um.removeEventListener("isUpdating", initUpgrade);
		}
		
		protected function hideWoots():void {
			currentWoot.visible = false;
			fadeOut.addEventListener(EffectEvent.EFFECT_END, showWoots);
		}
		
		protected function showWoots(event:String):void {
			currentWoot.visible = true;
			last10Woots.visible = true;
			fadeOut.removeEventListener(EffectEvent.EFFECT_END, showWoots);
		}
		
		protected function reloadWoot(event:String):void {
			blogService.send();
			currentWootService.send();
			dataRefreshIcon.source = loaderImage;
			dataRefreshIcon.x = 35;
			dataRefreshIcon.y = 645;
			this.addChild(dataRefreshIcon);
			wootTimer.stop();
		}
		
		protected function handleCurrentWootService(event:ResultEvent):void {
			var htmlHead:String = '<?xml version="1.0" encoding="utf-8"?><html><head><style>body{font-size: 11pt; font-family: calibri, Helvetica, Arial;}</style></head><body>';
			var htmlFoot:String = '</body></html>';
			
			currentWootDesc.htmlText = htmlHead + event.result.rss.channel.item.description + htmlFoot;
			
			if(lastWootResult.guid != undefined) {
				if(StringUtil.trim(lastWootResult.guid) != StringUtil.trim(event.result.rss.channel.item.guid)) {
					if(currentWoot.visible == true) {
						hideWoots();
					} else {
						currentWoot.visible = true;
					}
				}
			} else {
				currentWoot.visible = true;
			}
			
			
			if(event.result.rss.channel.item.soldout == true) {
				soldOutImg.visible = true;	
				soldOutImg.includeInLayout = true;	
			} else {
				percentSold.setProgress(event.result.rss.channel.item.soldoutpercentage, 1)
				soldOutImg.visible = false;	
				soldOutImg.includeInLayout = false;	
			}
			
			lastWootResult = event.result.rss.channel.item;
			this.removeChild(dataRefreshIcon);
			wootTimer.start();
		}
		
		
		protected function handleWootService(event:ResultEvent):void {
			
			if(event.result.rss.channel.item[0].enclosure != undefined) {
				if(wootPodcast.visible == false)
					wootPodcast.visible = true;
				
				if(wootPodcast.includeInLayout == false)
					wootPodcast.includeInLayout = true;
				
				podcastURL = event.result.rss.channel.item[0].enclosure.url;
			} else {
				if(wootPodcast.visible == true)
					wootPodcast.visible = false;
				
				if(wootPodcast.includeInLayout == false)
					wootPodcast.includeInLayout = false;
			}
			
			blogItems = event.result.rss.channel.item;
		}
		
		protected function faultWootService():void {
			Alert.show('Error loading Woot! XML feed');
		}
		
		protected function setDescription():void {
			var htmlHead:String = '<?xml version="1.0" encoding="utf-8"?><html><head><style>body{font-size: 11pt; font-family: calibri, Helvetica, Arial;}</style></head><body>';
			var htmlFoot:String = '</body></html>';
			currentWootDesc.htmlText = htmlHead + currentWootService.lastResult.rss.channel.item.description + htmlFoot;
		}
		
		protected function startWindowMove() : void {
			// disabled the position management when we are manually moving
			WindowBoundsManager.getInstance().disablePositionManagement();
			stage.nativeWindow.startMove();
		}
			
		protected function stopWindowMove() : void {
			// enable the positions management when we are done manually moving.
			WindowBoundsManager.getInstance().enablePositionManagement();
		}
		
		// creates the icon in the system tray
		private function setupSystemTrayIcon():void {
			
			if (NativeApplication.supportsSystemTrayIcon) {
				sysTrayIcon.tooltip = "YAWN";
				sysTrayIcon.bitmaps = [(new sysTrayIcon16() as Bitmap).bitmapData];
				sysTrayIcon.tooltip = "YAWN";
				sysTrayIcon.menu = new NativeMenu();
				
				sysTrayIcon.addEventListener("click",
					function(event:Event):void {
						stage.nativeWindow.visible = true;
						stage.nativeWindow.activate();
					}
				);
				

				var exitCommand:NativeMenuItem = sysTrayIcon.menu.addItem(new NativeMenuItem("Exit"));
				exitCommand.addEventListener(Event.SELECT,
				   	function(event:Event):void {
				  		 titleControls.closeApp();
					}
				);
			}
		}
		
		//connects us to the IRC channel
		protected function connect():void {
			var nickUseCount:Number = new Number();  //dw
			if(nickName.text.length)
			{
				hb_chat.removeChild(ircLoginWindow);
				chatConnect.visible = true;
				nickUseCount = dataManager.ircnickSubmitted(nickName.text); //dw
				//Alert.show("You have used the nick " + nickName.text + " a total of " + nickUseCount + " times"); //dw
				if(wootIRC.flexIrcClient == null) {
					var tmpIRCClient:FlexIrcClient = new FlexIrcClient();
					wootIRC.flexIrcClient = tmpIRCClient;
				}
				 
				if(wootIRC.flexIrcClient != null) {
					if(!wootIRC.flexIrcClient.isConnected()) {
						wootIRC.flexIrcClient.addEventListener("serverResponseEvent", serverReponse);
						wootIRC.flexIrcClient.connect("irc.gamesurge.net");
						wootIRC.flexIrcClient.setName(nickName.text);
					}
				}
			}
		}
		
		protected function joinChannel():void {
			wootIRC.flexIrcClient.joinChannel("#woot");
		}
		
		//monitors the IRC connection for responses sent to us from the server
		private function serverReponse(evt:*): void {
			if(evt.code == "255") {
				joinChannel();
				wootIRC.channel = "#woot";
				hb_chat.removeChild(chatConnect);
				wootIRC.styleName = "ircChatBox";
				hb_chat.addChild(wootIRC);
			}
		}
		
		//tells the UpdateManager to stop listening for update events
		private function stopListeningForUpdates(evt:Event):void {
			//um.removeEventListener("updaterComplete", stopListeningForUpdates);
			//um.removeEventListener("isUpdating", initUpgrade);
		}
	}
}